package com.bskyb.rss.parser;

import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.bskyb.rss.FeedItem;
import com.bskyb.rss.RssFeed;



public class RssFeedHandler extends DefaultHandler {
	
	// Used to define what elements we are currently in
	private boolean inTitle = false;
	private boolean inLink = false;
	private boolean inDescription = false;
	private boolean inItem = false;
	
	
	private RssFeed rssFeed = new RssFeed();
	private FeedItem currentFeedItem;
	private String TAG = "RssFeedHandler";
	
	@Override
	public void startElement(String uri, String name, String qName,
			Attributes atts) {
		if (name.trim().equals("title")){
			inTitle = true;
		}
		else if (name.trim().equals("description")){
			inDescription = true;
		}	
		else if (name.trim().equals("link")){
			inLink = true;
		}
		else if (name.trim().equals("item")){
			inItem = true;
			currentFeedItem = new FeedItem();
		}
			
	}

	@Override
	public void endElement(String uri, String name, String qName)
			throws SAXException {
		if (name.trim().equals("title")){
			inTitle = false;
		}	
		else if (name.trim().equals("description")){
			inDescription = false;
		}			
		else if (name.trim().equals("link")){
			inLink = false;
		}else if (name.trim().equals("item")){
			inItem = false;
			rssFeed.addFeedItem(currentFeedItem);
		}
		
			
	}

	@Override
	public void characters(char ch[], int start, int length) {
		String chars = (new String(ch).substring(start, start + length));
			if (inItem) {
				if (inTitle) {
					currentFeedItem.setTitle(chars);
				} else if (inLink) {
					currentFeedItem.setLink(chars);
				} else if (inDescription){
					currentFeedItem.setDescription(chars);
				}
				
			}		
	}
	
	public RssFeed createFeed(URL url) {
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			xr.setContentHandler(this);
			InputSource inputSource = new InputSource(url.openStream());			
			xr.parse(inputSource);
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("RssFeedHandler", e.toString());
		} catch (SAXException e) {
			e.printStackTrace();
			Log.e("RssFeedHandler", e.toString());
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			Log.e("RssFeedHandler", e.toString());
		}		
		return rssFeed;
	}	

}
